/**
 * Alibaba.com.cn Inc.
 * Copyright (c) 2004-2021 All Rights Reserved.
 */
package com.hiv.utils;

import com.itextpdf.text.BadElementException;
import com.itextpdf.text.Document;
import com.itextpdf.text.DocumentException;
import com.itextpdf.text.Element;
import com.itextpdf.text.Font;
import com.itextpdf.text.Image;
import com.itextpdf.text.Paragraph;
import com.itextpdf.text.Phrase;
import com.itextpdf.text.Rectangle;
import com.itextpdf.text.pdf.AcroFields;
import com.itextpdf.text.pdf.AcroFields.Item;
import com.itextpdf.text.pdf.BaseFont;
import com.itextpdf.text.pdf.PdfContentByte;
import com.itextpdf.text.pdf.PdfImportedPage;
import com.itextpdf.text.pdf.PdfPCell;
import com.itextpdf.text.pdf.PdfPTable;
import com.itextpdf.text.pdf.PdfReader;
import com.itextpdf.text.pdf.PdfStamper;
import com.itextpdf.text.pdf.PdfWriter;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

/**
 * @author zhanghong
 * @version PDFUtils.java, v 0.1 2023/3/26 21:56 下午 PDFUtils Exp $$
 */
public class PDFUtils {
    /**
     * @param fields
     * @param data
     * @throws IOException
     * @throws DocumentException
     */
    private static void fillData(AcroFields fields, Map<String, String> data) throws IOException, DocumentException {
        List<String> keys = new ArrayList<String>();
        Map<String, Item> formFields = fields.getFields();
        for (String key : data.keySet()) {
            if (formFields.containsKey(key)) {
                String value = data.get(key);
                fields.setField(key, value); // 为字段赋值,注意字段名称是区分大小写的
                keys.add(key);
            }
        }
        Iterator<String> itemsKey = formFields.keySet().iterator();
        while (itemsKey.hasNext()) {
            String itemKey = itemsKey.next();
            if (!keys.contains(itemKey)) {
                fields.setField(itemKey, " ");
            }
        }
    }

    //为一个表格添加内容
    public static PdfPCell createSetCell(String value, Font font){
        PdfPCell cell = new PdfPCell();
        cell.setPhrase(new Phrase(value,font));
        cell.setVerticalAlignment(Element.ALIGN_MIDDLE);
        cell.setHorizontalAlignment(Element.ALIGN_CENTER);
        return cell;
    }

    /**
     * @param fields
     * @param data
     * @throws IOException
     * @throws DocumentException
     */
    //private static void fillTable(AcroFields fields, Map<String, String> data) throws IOException, DocumentException {
    //    PdfPTable table = new PdfPTable(new float[] { 30, 80, 50, 50, 50});
    //    table.setTotalWidth(520);
    //    table.setPaddingTop(500);
    //    table.setLockedWidth(true);
    //    table.setHorizontalAlignment(Element.ALIGN_CENTER);//居中
    //    table.writeSelectedRows(0, -1,500,800,writer.getDirectContentUnder());
    //    //每页都显示表头,输入几就是第几行的表头固定
    //    table.setHeaderRows(2);
    //    table.setHeaderRows(3);
    //
    //    //定义数据的字体
    //    BaseFont baseFont = BaseFont.createFont("STSong-Light","UniGB-UCS2-H",BaseFont.NOT_EMBEDDED);
    //    Font textFont = new Font(baseFont, 10, Font.NORMAL);
    //    PdfPCell cell = new PdfPCell(new Paragraph(" ", textFont));
    //
    //    cell.setHorizontalAlignment( Element.ALIGN_LEFT);
    //
    //    cell.setVerticalAlignment(Element.ALIGN_BOTTOM);
    //
    //    cell.setBorder(Rectangle.NO_BORDER);
    //
    //    cell.setColspan(5);
    //
    //    table.addCell(cell);
    //
    //    //表头信息
    //    PdfPCell heandCell = new PdfPCell();
    //    heandCell.setRowspan(1);
    //    heandCell.setColspan(5);
    //    heandCell.setFixedHeight(60);
    //    heandCell.setVerticalAlignment(Element.ALIGN_MIDDLE);
    //    heandCell.setHorizontalAlignment(Element.ALIGN_CENTER);
    //    heandCell.setPhrase(new Phrase(TITLE + "对账情况表",textFont));
    //    table.addCell(heandCell);
    //
    //    //表字段
    //    String title[] = {"序号","机构","已对账","未对账","对账率%"};
    //    for (int i = 0; i < title.length; i++) {
    //        PdfPCell heardCell = new PdfPCell();
    //        heardCell.setVerticalAlignment(Element.ALIGN_MIDDLE);
    //        heardCell.setHorizontalAlignment(Element.ALIGN_CENTER);
    //        heardCell.setPhrase(new Phrase(title[i], textFont));
    //        heardCell.setMinimumHeight(20);
    //        table.addCell(heardCell);
    //    }
    //
    //    //列表数据
    //
    //    List<DuizhangDomain> duizhangDomains = new ArrayList<>();
    //    for (int i = 1; i <= 1000; i++) {
    //        DuizhangDomain duizhangDomain = new DuizhangDomain();
    //        duizhangDomain.setJg("机构" + i).setYdz(i).setWdz(i).setDzl(new BigDecimal(i));
    //        duizhangDomains.add(duizhangDomain);
    //    }
    //
    //    for (int i = 0; i < duizhangDomains.size(); i++) {
    //        PdfPCell setCell1 = createSetCell((i + 1) + "", textFont);
    //        PdfPCell setCell2 = createSetCell(duizhangDomains.get(i).getJg(), textFont);
    //        PdfPCell setCell3 = createSetCell(duizhangDomains.get(i).getYdz().toString(), textFont);
    //        PdfPCell setCell4 = createSetCell(duizhangDomains.get(i).getWdz().toString(), textFont);
    //        PdfPCell setCell5 = createSetCell(duizhangDomains.get(i).getDzl() + "%", textFont);
    //        table.addCell(setCell1);
    //        table.addCell(setCell2);
    //        table.addCell(setCell3);
    //        table.addCell(setCell4);
    //        table.addCell(setCell5);
    //    }
    //    document.add(table);
    //}

    private static void fillSign(PdfStamper ps, AcroFields fields, Map<String, String> imageData) throws DocumentException, IOException {
        //添加图片
        PdfContentByte cb = ps.getOverContent(3);
        imageData.forEach((fieldName, imageUrl) -> {
            try {
                if (imageUrl != null) {
                    //添加编制人签名
                    Rectangle bianzhiSign = fields.getFieldPositions(fieldName).get(0).position;
                    Image bianzhiSignImage = null;
                    bianzhiSignImage = Image.getInstance(imageUrl);
                    //根据域的大小缩放图片，我这里宽度在原有的域基础上加了100，你们可以自己调节
                    bianzhiSignImage.scaleToFit(bianzhiSign.getWidth() + 100,bianzhiSign.getHeight());
                    bianzhiSignImage.setAlignment(Image.MIDDLE);
                    bianzhiSignImage.setAbsolutePosition(bianzhiSign.getLeft(),bianzhiSign.getBottom());
                    cb.addImage(bianzhiSignImage);
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        });
    }
    /**
     * @param templatePdfPath 模板pdf路径
     * @param generatePdfPath 生成pdf路径
     * @param textData            数据
     */
    public static String generatePDF(String templatePdfPath, String generatePdfPath, Map<String, String> textData, Map<String, String> imageData) {
        OutputStream fos = null;
        ByteArrayOutputStream bos = new ByteArrayOutputStream();
        try {
            PdfReader reader = new PdfReader(templatePdfPath);
            /* 将要生成的目标PDF文件名称 */
            PdfStamper ps = new PdfStamper(reader, bos);
            /* 使用中文字体 */
            BaseFont bf = BaseFont.createFont("STSong-Light", "UniGB-UCS2-H", BaseFont.NOT_EMBEDDED);
            ArrayList<BaseFont> fontList = new ArrayList<>();
            fontList.add(bf);
            /* 取出报表模板中的所有字段 */
            AcroFields fields = ps.getAcroFields();
            fields.setSubstitutionFonts(fontList);
            fillData(fields, textData);//填充文本
            fillSign(ps, fields, imageData);//填充签名图片

            ////创建一个新的页
            //reader = new PdfReader(bos.toByteArray());
            //Rectangle pageSize = reader.getPageSize(1);
            //Document document = new Document(pageSize);
            //PdfWriter writer = PdfWriter.getInstance(document, bos);
            //writer.setPageEvent(new PageEvent());
            //// 打开文档
            //document.open();
            //PdfContentByte cbUnder = writer.getDirectContentUnder();
            //PdfImportedPage pageTemplate = writer.getImportedPage(reader, 1);
            //cbUnder.addTemplate(pageTemplate, 0, 0);
            ////重新开一页面
            //document.newPage();
            //createTable(writer,document);
            //document.close();

            /* 必须要调用这个，否则文档不会生成的  如果为false那么生成的PDF文件还能编辑，一定要设为true*/
            ps.setFormFlattening(true);
            ps.close();

            File file = new File(generatePdfPath);
            if (!file.getParentFile().exists()) {
                file.getParentFile().mkdirs();
            }

            fos = new FileOutputStream(generatePdfPath);
            fos.write(bos.toByteArray());
            fos.flush();
            return generatePdfPath;
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (fos != null) {
                try {
                    fos.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if (bos != null) {
                try {
                    bos.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return null;
    }

    public static void createTable(PdfWriter writer,Document document) throws DocumentException, IOException {

        PdfPTable table = new PdfPTable(new float[] {80, 50});
        table.setTotalWidth(520);
        table.setPaddingTop(500);
        table.setLockedWidth(true);
        table.setHorizontalAlignment(Element.ALIGN_CENTER);//居中
        table.writeSelectedRows(0, -1,500,800,writer.getDirectContentUnder());
        //每页都显示表头,输入几就是第几行的表头固定
        table.setHeaderRows(2);
        table.setHeaderRows(3);

        //定义数据的字体
        BaseFont baseFont = BaseFont.createFont("STSong-Light","UniGB-UCS2-H",BaseFont.NOT_EMBEDDED);
        Font textFont = new Font(baseFont, 10, Font.NORMAL);

        //这个是为了区分两个表格加的一个间隔，可以去掉
        PdfPCell cell = new PdfPCell(new Paragraph(" ", textFont));
        cell.setHorizontalAlignment( Element.ALIGN_LEFT);
        cell.setVerticalAlignment(Element.ALIGN_BOTTOM);
        cell.setBorder(Rectangle.NO_BORDER);
        cell.setColspan(2);
        table.addCell(cell);

        //表头信息
        PdfPCell heandCell = new PdfPCell();
        heandCell.setRowspan(1);
        heandCell.setColspan(2);
        heandCell.setFixedHeight(60);
        heandCell.setVerticalAlignment(Element.ALIGN_MIDDLE);
        heandCell.setHorizontalAlignment(Element.ALIGN_CENTER);
        heandCell.setPhrase(new Phrase("逾期表",textFont));
        table.addCell(heandCell);

        //表字段
        String title[] = {"机构名称","逾期数"};
        for (int i = 0; i < title.length; i++) {
            PdfPCell heardCell = new PdfPCell();
            heardCell.setVerticalAlignment(Element.ALIGN_MIDDLE);
            heardCell.setHorizontalAlignment(Element.ALIGN_CENTER);
            heardCell.setPhrase(new Phrase(title[i], textFont));
            heardCell.setMinimumHeight(20);
            table.addCell(heardCell);
        }

        //列表数据

        List<YqTable> yqTables = new ArrayList<>();
        for (int i = 1; i <= 1000; i++) {
            YqTable yq = new YqTable();
            yq.setJg("逾期机构" + i).setYqs(i);
            yqTables.add(yq);
        }

        for (int i = 0; i < yqTables.size(); i++) {
            PdfPCell setCell2 = createSetCell(yqTables.get(i).getJg(), textFont);
            PdfPCell setCell3 = createSetCell(yqTables.get(i).getYqs().toString(), textFont);
            table.addCell(setCell2);
            table.addCell(setCell3);
        }
        document.add(table);
    }

    public static void main(String[] args) {
        Map<String, String> textData = new HashMap<>();
        //key为pdf模板的form表单的名字，value为需要填充的值
        textData.put("reportNum", "123123");
        textData.put("samplingName", "123123");
        textData.put("inspectionCategory", "123123");
        textData.put("baseEntrustUnit", "123123");
        textData.put("baseInspectionUnit", "123123");
        textData.put("baseUnitAddress", "123123");
        textData.put("baseUnitEmail", "123123");
        textData.put("baseUnitPhone", "123123");
        textData.put("reportInfo", "123123");
        textData.put("symbolInspectBasis", "123123");
        textData.put("symbolInspectDevice", "123123");
        textData.put("storageTime", "我是收样时间");
        textData.put("inspectionTime", "我是检测时间");
        textData.put("symbolInspectResult", "我是：检测结论");
        textData.put("symbolRemark", "我是：备注");
        textData.put("piZhunDate", "我是：批准日期");
        textData.put("reportResult", "我是：检测报告");//table
        textData.put("reportRemark", "我是：检测备注");

        Map<String, String> imageData = new HashMap<>();
        imageData.put("bianzhiSign", "https://img1.baidu.com/it/u=3646261857,3326755268&fm=253&app=138&size=w931&n=0&f=JPG&fmt=auto?sec=1668186000&t=20050fc88fc3feb1f9d28392f4595ec6");
        imageData.put("shenHeSign", "https://img1.baidu.com/it/u=3646261857,3326755268&fm=253&app=138&size=w931&n=0&f=JPG&fmt=auto?sec=1668186000&t=20050fc88fc3feb1f9d28392f4595ec6");
        imageData.put("piZhunSign", "https://img1.baidu.com/it/u=3646261857,3326755268&fm=253&app=138&size=w931&n=0&f=JPG&fmt=auto?sec=1668186000&t=20050fc88fc3feb1f9d28392f4595ec6");

        //generatePDF("/Users/zhanghong/Desktop/report.pdf", "/Users/zhanghong/Desktop/report2.pdf", textData, imageData);
        generatePDF("/Users/zhanghong/Desktop/report.pdf", "/Users/zhanghong/Desktop/test_new.pdf", textData, imageData);
    }
}
